<template>
    <div v-if="step == 'HOME'">
        <ConditionCard
            body-style="padding: 24px"
            class="groupList-addUser"
            @search="queryTableList"
            @reset="reset"
        >
            <el-form ref="queryForm" :model="queryForm" label-width="80px" label-suffix="：">
                <el-row :gutter="2">
                    <el-col :span="8">
                        <el-form-item :label="$t('schoolAdministration.yearAndSemester')">
                            <CalendarSelect
                                v-model="queryForm.condition.calendarId"
                            ></CalendarSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item :label="$t('schoolAdministration.auditStatus')">
                            <DictSelect
                                labelAll="请选择"
                                v-model="queryForm.condition.status"
                                :data="options.status"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </ConditionCard>
        <el-card>
            <el-row type="flex" justify="space-between" align="center" style="margin-bottom:16px">
                <el-col :span="12">
                    <h1 slot="header">{{$t('schoolAdministration.creditRecognitionList')}}</h1>
                </el-col>
                <el-col :span="12" style="text-align:right">
                    <el-button @click="handleClick('AB')" type="primary">{{$t('schoolAdministration.applyBehalf')}}</el-button>
                    <el-button @click="handleClick('EX')" type="primary">{{$t('schoolAdministration.clickUpload')}}</el-button>
                </el-col>
            </el-row>
            <edu-table
                :data="tableList"
                :total="queryForm.total_"
                :pageSize="queryForm.pageSize_"
                @page-change="onCurrentPageChange"
                @selection-change="handleSelectionChange"
            >
                <el-table-column :label="$t('schoolAdministration.studentNumber')" prop="studentId" width="80"></el-table-column>
                <el-table-column
                    :label="$t('schoolAdministration.fullName')"
                    prop="studentName"
                    width="80"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('schoolAdministration.exchangeName')"
                    prop="exchangeName"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('schoolAdministration.oldCourseStr')"
                    prop="oldCourseStr"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    :label="$t('schoolAdministration.cognizanceYearAndSemester')"
                    width='170'
                    show-overflow-tooltip
                >
                    <template slot-scope="scope">
                        <span>{{ scope.row.newCourseList[0] && scope.row.newCourseList[0].identifyCalendarName }}</span>
                    </template>
                </el-table-column>
                <el-table-column  :label="$t('schoolAdministration.identifyCourses')" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{ scope.row.newCourseList[0] && scope.row.newCourseList[0].courseName }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('schoolAdministration.recognitionResults')"  show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>
                            {{
                                getStatus(
                                    'scoreTypeList',
                                    scope.row.newCourseList[0] && scope.row.newCourseList[0].newCourseScore
                                ) &&
                                    getStatus(
                                        'scoreTypeList',
                                        scope.row.newCourseList[0] && scope.row.newCourseList[0].newCourseScore
                                    )['label']
                            }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('exchangeApproval.reviewer')" show-overflow-tooltip min-width="120" fixed="right">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="medium"
                            v-if="!scope.row.assignApprover"
                            @click.stop="showApproveGroup(scope.row.approver)"
                        > 
                            {{ scope.row.approveName }}
                        </el-button>
                        <span v-else>{{ scope.row.assignApproverName + '(' + scope.row.assignApprover + ')' }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('schoolAdministration.auditStatus')" fixed="right">
                    <template slot-scope="scope">
                        <el-tag :type="getStatus('status', scope.row.approvalStatus)['type']">
                            {{ getStatus('status', scope.row.approvalStatus)['label'] }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('schoolAdministration.operate')" fixed="right" width="100px">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click.stop="handleOperate('AUDIT', scope.row)"
                            v-if="
                                scope.row.canAudit &&
                                    (scope.row.approvalStatus == 1 || scope.row.approvalStatus == 4)
                            "
                        >
                            {{$t('schoolAdministration.toExamine')}}
                        </el-button>
                        <el-button
                            type="text"
                            v-if="!scope.row.approvalStatus"
                            @click="handleOperate('EDIT', scope.row)"
                        >
                            {{$t('schoolAdministration.edit')}}
                        </el-button>
                        <el-button type="text" @click.stop="handleOperate('VIEW', scope.row)">
                            {{$t('schoolAdministration.check')}}
                        </el-button>
                    </template>
                </el-table-column>
            </edu-table>
        </el-card>
        <approve-group :visible.sync="approveGroupDialog.visible" :groupId="approveGroupDialog.groupId" v-if="approveGroupDialog.visible"></approve-group>
        <el-dialog
            :title="$t('schoolAdministration.designatedReviewer')"
            :visible.sync="designReviewerDialog.visible"
            width="40%"
            :before-close="handleClose"
        >
            <el-form
                label-suffix="："
                :model="designReviewerDialog"
                label-position="right"
                ref="designReviewerDialog"
                label-width="100px"
            >
                <el-form-item
                    prop="teacherValue"
                    :label="$t('schoolAdministration.teacher')"
                    :rules="[
                        {
                            required: true,
                            message: this.$t('schoolAdministration.pleaseEnterTeacher'),
                            trigger: ['blur', 'change']
                        }
                    ]"
                >
                    <el-autocomplete
                        style="width:90%"
                        v-model="designReviewerDialog.teacherValue"
                        :fetch-suggestions="querySearchAsync"
                        :placeholder="$t('schoolAdministration.pleaseEnterTeacherId')"
                        @select="handleSelect"
                    ></el-autocomplete>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">{{$t('schoolAdministration.cancel')}}</el-button>
                <el-button type="primary" @click="handleClick('DRS')">{{$t('schoolAdministration.determine')}}</el-button>
            </span>
        </el-dialog>
    </div>
    <div v-else>
        <el-row type="flex" justify="space-between">
            <el-col :span="12">
                {{$t('schoolAdministration.approvalAndAgent')}}
            </el-col>
            <el-col :span="12" style="text-align:right">
                <el-button type="text" @click="step = 'HOME'">{{$t('schoolAdministration.back')}}</el-button>
            </el-col>
        </el-row>
        <el-card
            body-style="display: flex;
                        flex-direction: column;
                        align-items: center;"
        >
            <h2 slot="header">{{$t('schoolAdministration.agencyApplication')}}</h2>
            <el-form
                label-suffix="："
                :model="behalfForm"
                label-position="right"
                ref="behalfForm"
                label-width="100px"
            >
                <el-form-item
                    :label="$t('schoolAdministration.studentNumber')"
                    prop="studentId"
                    :rules="[
                        {
                            required: true,
                            message: this.$t('schoolAdministration.pleaseSearchTeacherId'),
                            trigger: ['change', 'blur']
                        }
                    ]"
                >
                    <KeywordInput
                        v-model="behalfForm.studentId"
                        :placeholder="$t('schoolAdministration.pleaseEnterstudentId')"
                        @enter="queryStudentInfo"
                    />
                </el-form-item>
                <el-form-item :label="$t('schoolAdministration.fullName')" prop="studentName">
                    <el-input
                        style="width:250px"
                        disabled
                        v-model="behalfForm.studentName"
                    ></el-input>
                </el-form-item>
                <el-form-item :label="$t('schoolAdministration.grade')" prop="grade">
                    <el-input style="width:250px" disabled v-model="behalfForm.grade"></el-input>
                </el-form-item>
                <el-form-item :label="$t('schoolAdministration.college')" prop="facultyI18n">
                    <el-input
                        style="width:250px"
                        disabled
                        v-model="behalfForm.facultyI18n"
                    ></el-input>
                </el-form-item>
                <el-form-item :label="$t('schoolAdministration.major')" prop="professionI18n">
                    <el-input
                        style="width:250px"
                        disabled
                        v-model="behalfForm.professionI18n"
                    ></el-input>
                </el-form-item>
                <el-form-item :label="$t('schoolAdministration.sex')"  prop="sexI18n">
                    <el-input style="width:250px" disabled v-model="behalfForm.sexI18n"></el-input>
                </el-form-item>
            </el-form>
            <span>
                <el-button @click="handleClickBehalfForm('RESET')">{{$t('schoolAdministration.reset')}}</el-button>
                <el-button
                    type="primary"
                    :disabled="!behalfForm.visible"
                    @click="handleClickBehalfForm('ADD')"
                >
                     {{$t('schoolAdministration.applyBehalf')}}
                </el-button>
            </span>
        </el-card>
    </div>
</template>
<script>
import UTILS from 'common/src/utils/utils'
import { findTeacherInfoList } from 'common/src/api/studentinfo'
import { assign, cancel, queryStuInfo, recall } from 'common/src/api/internationalExchanges/exchangeApproval'
import {
    getTableList,
    getScopeTypeList,
    exportApplyList,
    checkTimeConfig
} from 'common/src/api/internationalExchanges/creditApplication.js'
export default {
    data() {
        return {
            step: 'HOME', //HOME:学分认定审核页面；BEHALF:待申请页
            queryForm: {
                total_: 0,
                pageNum_: 1,
                pageSize_: 20,
                condition: {
                    ids: [],
                    calendarId: '',
                    queryType: '1',
                    status: ''
                }
            },
            tableList: [],
            multipleSelection: [],
            behalfForm: {
                visible: false,
                studentId: '',
                studentName: '',
                grade: '',
                faculty: '',
                facultyI18n: '',
                profession: '',
                professionI18n: '',
                sex: '',
                sexI18n: ''
            },
            designReviewerDialog: {
                visible: false,
                teacherValue: '',
                teacherObj: {}
            },
            options: {
                status: [
                    {
                        value: 0,
                        label: '草稿',
                        type: 'info'
                    },
                    {
                        value: 1,
                        label: '审核中',
                        type: ''
                    },
                    {
                        value: 2,
                        label: '已驳回',
                        type: 'warning'
                    },
                    {
                        value: 3,
                        label: '已通过',
                        type: 'success'
                    },
                    {
                        value: 4,
                        label: '已提交',
                        type: 'success'
                    }
                ],
                scoreTypeList: []
            },
            approveGroupDialog: {
                visible: false,
                groupId: ''
            }
        }
    },
    components: {
        'approveGroup': resolve => require(['./component/approveGroup'], resolve)
    },
    mounted() {
        this.init()
    },
    methods: {
        async init() {
            await this.queryScopeTypeList()
            await this.queryTableList()
        },
        async queryScopeTypeList() {
            let { code, data } = await getScopeTypeList()
            if (code !== 200) return
            this.options.scoreTypeList =
                data[0] &&
                data[0].scoreDetail.map(item => {
                    return {
                        value: item.scoreNum,
                        label: item.scoreName
                    }
                })
        },
        getStatus(exp, value = 0) {
            let list = this.options[exp]
            let obj = list.find(item => item.value == value)
            return obj || {}
        },
        async queryTableList(params = this.queryForm) {
            let { code, data } = await getTableList(params)
            if (code !== 200) return
            data.list.forEach(ele => {
                ele.newCourseList = ele.newCourseList || [];
                ele.newCourseList.forEach(item => {
                    ;(item.courseCode = item.newCourseCode),
                        (item.courseName = item.newCourseName),
                        (item.creidits = item.newCredit)
                })
                ele.oldCourseStr = '';
                (ele.oldCourseList || []).forEach((item, index) => {
                    if (ele.oldCourseList.length == index + 1) {
                        ele.oldCourseStr += item.oldCourseName
                    } else {
                        ele.oldCourseStr += `${item.oldCourseName}、`
                    }
                })
            })
            this.tableList = data.list
            this.queryForm.total_ = data.total_
            this.queryForm.pageNum_ = data.pageNum_
            this.queryForm.pageSize_ = data.pageSize_
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
            this.queryForm.condition.ids = val.map(item => item.id)
        },
        onCurrentPageChange(pager) {
            this.queryForm.pageSize_ = pager.pageSize
            this.queryForm.pageNum_ = pager.pageNum
            this.queryTableList()
        },
        async querySearchAsync(queryString, cb) {
            let result
            let params = { condition: queryString, pageNum_: 1, total: 0, pageSize_: 20 }
            let { code, data } = await findTeacherInfoList(params)
            result = data.list.map(item => {
                return {
                    auditorName: item.name,
                    auditorId: item.code,
                    value: `${item.name}(${item.code})${item.facultyI18n}`
                }
            })
            cb(result)
        },
        handleSelect(item) {
            this.designReviewerDialog.teacherObj = item
        },

        handleClickBehalfForm(mode) {
            switch (mode) {
                case 'ADD':
                    this.$refs['behalfForm'].validate(valid => {
                        if (valid) {
                            checkTimeConfig().then(res => {
                                if (res.code == 200) {
                                    if (res.data.allowFlag) {
                                        this.$router.push({
                                            path: '/UGIECreditDetail',
                                            query: {
                                                mode,
                                                type: 1,
                                                studentInfo: {
                                                    studentName: this.behalfForm.studentName,
                                                    studentId: this.behalfForm.studentId,
                                                    grade: this.behalfForm.grade
                                                }
                                            }
                                        })
                                    } else {
                                        this.$message({
                                            type: 'warning',
                                            message: '当前时间未在申请时间段内，请联系管理员'
                                        })
                                    }
                                }
                            })
                        } else {
                            return false
                        }
                    })
                    break
                case 'RESET':
                    this.$refs['behalfForm'] && this.$refs['behalfForm'].resetFields()
                    break
            }
        },
        handleClick(mode) {
            let len = this.multipleSelection.length
            switch (mode) {
                //指定审核人
                case 'DR':
                    if (!len) {
                        this.$message({
                            type: 'warning',
                            message: '请先选择需要指定审核人的列表记录'
                        })
                        return
                    }
                    if (!this.checkStatus(1, 'approvalStatus', this.multipleSelection)) {
                        this.$message({
                            type: 'warning',
                            message: '只有审核中状态的列表才能进行此操作'
                        })
                        return
                    }
                    this.designReviewerDialog.visible = !this.designReviewerDialog.visible
                    break
                //指定审核人提交
                case 'DRS':
                    this.$refs['designReviewerDialog'].validate(valid => {
                        if (valid) {
                            let obj = this.designReviewerDialog.teacherObj
                            let ids = this.multipleSelection.map(item => item.id)
                            let list = this.multipleSelection.map(item => item.workflowNo)
                            let params = {
                                type: '2',
                                ids: ids,
                                auditorId: obj.auditorId,
                                auditorName: obj.auditorName,
                                workflowNo: list
                            }
                            this.designReviewer(mode, params)
                            this.designReviewerDialog.visible = !this.designReviewerDialog.visible
                            this.reset()
                        } else {
                            return false
                        }
                    })
                    break
                //取消指定
                case 'CD':
                    if (!len) {
                        this.$message({
                            type: 'warning',
                            message: '请先选择需要取消指定审核人的列表记录'
                        })
                        return
                    }
                    if (!this.checkStatus(4, 'approvalStatus', this.multipleSelection)) {
                        this.$message({
                            type: 'warning',
                            message: '只有审核中状态的列表才能进行此操作'
                        })
                        return
                    }
                    this.$confirm('此操作将取消所选列表指定审核人, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                        .then(() => {
                            let params = {
                                type: '2',
                                ids: this.multipleSelection.map(item => item.id),
                                auditorIdList: this.multipleSelection.map(item => item.approver),
                                workflowNo: this.multipleSelection.map(item => item.workflowNo)
                            }
                            this.designReviewer(mode, params)
                        })
                        .catch(() => {})

                    break
                //代申请
                case 'AB':
                    this.step = 'BEHALF'
                    break
                //导出
                case 'EX':
                    exportApplyList(
                        Object.assign(this.queryForm.condition, {
                            exportType: '0'
                        })
                    )
                    break
            }
        },
        handleSelect(item) {
            this.designReviewerDialog.teacherObj = item
        },
        handleOperate(mode, data) {
            switch (mode) {
                case 'EDIT':
                    let studentInfo = {
                        grade: data.grade,
                        studentName: data.studentName,
                        studentId: data.studentId
                    }
                    this.$router.push({
                        path: '/UGIECreditDetail',
                        query: {
                            mode,
                            data,
                            type: 1,
                            studentInfo
                        }
                    })
                    break
                //审核、查看
                case 'AUDIT':
                case 'VIEW':
                    this.$router.push({
                        path: 'UGIECreditDetail',
                        query: {
                            data,
                            mode,
                            studentInfo: {
                                studentId: data.studentId,
                                grade: data.grade
                            }
                        }
                    })
                    break
            }
        },
        checkStatus(typeValue, filed, list) {
            return list.every(item => item[filed] == typeValue)
        },
        async queryStudentInfo(id) {
            let { code, data, msg } = await queryStuInfo({
                studentId: id,
                isIllegal: true,
                isCurrentFaculty: true,
                isUndergraduate: true
            })
            if (code !== 200) return
            if (!data) {
                this.behalfForm.visible = !!data
                this.$eduAlert(msg)
            } else {
                this.behalfForm.visible = !!data
            }
            for (let key in this.behalfForm) {
                if (key !== 'visible') {
                    this.behalfForm[key] = data ? data[key] : ''
                }
            }
        },
        async designReviewer(mode, params) {
            let request = mode == 'DRS' ? assign(params) : cancel(params)
            let { code, data } = await request
            if (code !== 200) return
            this.$message({
                type: 'success',
                message: mode == 'DRS' ? '指定审核人成功' : '取消指定审核人成功'
            })
            this.queryTableList()
        },
        reset() {
            let condition = this.queryForm.condition
            for (let key in condition) {
                if (key == 'ids') {
                    condition[key] = []
                } else if(key=='status') {
                    condition[key] = ''
                }
            }
            this.queryForm.total_ = 0
            this.queryForm.pageNum_ = 1
            this.queryForm.pageSize_ = 20
            this.queryTableList()
        },
        showApproveGroup(id) {
            this.approveGroupDialog.visible = true;
            this.approveGroupDialog.groupId = id;
        }
    }
}
</script>
<style lang="scss" scoped>
</style>
